<template>
  <div class="app-container">
    <el-form :model="param" :inline="true" label-width="68px">
      <el-form-item style="width:240px">
        <div>订单号</div>
        <el-input v-model.trim="param.orderNo" clearable  placeholder="请输入"> </el-input>
        <!-- <MultipleBoxNumbersDialog v-model="param.orderNo" :multipleBoxInfo="customBoxInfo"/> -->
      </el-form-item>
      <el-form-item style="width:240px">
        <div>结算流向</div>
        <el-select v-model="param.invoiceDirection" style="width:100%" placeholder="请选择">
          <el-option v-for="item in param.invoiceDirections" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>结算单位</div>
        <el-input v-model.trim="param.businessName" clearable  placeholder="请输入"> </el-input>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>发票号</div>
        <el-input v-model.trim="param.invoiceNoSearch" clearable placeholder="请输入"> </el-input>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>发票状态</div>
        <el-select v-model="param.invoiceStatus" style="width:100%" placeholder="请选择">
          <el-option v-for="item in param.invoiceStatuss" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>发票类型</div>
        <el-select v-model="param.invoiceType" clearable style="width:100%" placeholder="请选择">
          <el-option v-for="item in param.invoiceTypes" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>纳税人识别号</div>
        <el-input v-model.trim="param.creditCode" clearable  placeholder="请输入"> </el-input>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>申请日期</div>
        <el-date-picker v-model="param.createDate" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item style="width:240px">
        <div>结算状态</div>
        <el-select v-model="param.closeStatus" style="width:100%" placeholder="请选择">
          <el-option v-for="item in param.closeStatuss" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleReset" :icon="Refresh" style="margin-top: 30px">重置</el-button>
        <el-button @click="getTableData" :icon="Search" type="primary" style="margin-top: 30px">查询</el-button>
      </el-form-item>
    </el-form>

    <div>
      <cz-tages :bottomLine="true" :typeList="param.typeList" @handleTypeChange="handleTypeChange" style="float: left;"></cz-tages>
      <span style="margin-top: -40px;float: right;">
        <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有集装箱" placement="left">
          <template v-if="isSelectAll">
            <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
          </template>
          <template v-else>
              <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
          </template>
        </el-tooltip>
        <el-button type="primary" size="small" style="width:80px" :disabled="!selection.length" plain round @click="toExportInvoice">导出</el-button>
      </span>
      <Table ref="tableRef" v-bind="table" :allId="allId" :isAllCheck="isAllCheck" @pageChange="onTablePageChange" @activInfo="activInfo" @activPay="activPay"
        @showInvoice="showInvoice" @applyInvoice="applyInvoice" @reInvoice="reInvoice"
        @applyRedInvoice="applyRedInvoice" @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
      </Table>
    </div>

    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible">
      <div v-if="param.oprType == 'img'">
        <pdfViewer v-for="item in param.pdfUrl" :url="item.url"></pdfViewer>
      </div>
      <!-- 售箱款 -->
      <div v-if="param.oprType == 'sellBoxFee'">
        <span class="_before">售箱款</span>
        <h3>明细</h3>
        <!-- <el-table :data="param.sellBoxFeeTotal">
          <el-table-column prop="needPayContainerNum" label="应收箱量" width="120"> </el-table-column>
          <el-table-column prop="dealAmount" label="应收售箱款总计"> </el-table-column>
          <el-table-column prop="deductAmount" label="实收售箱款总计"> </el-table-column>
          <el-table-column prop="couponAmount" label="优惠券" width="120">
            <template #default="scope">
              {{ scope.row.couponAmount || '无' }}
            </template>
          </el-table-column>
        </el-table> -->
        <!-- <b>售箱款明细</b> -->
        <el-table :data="param.sellBoxFeeDetail" align="center">
            <!-- <el-table-column type="index" label="序号" width="60"> </el-table-column> -->
            <el-table-column prop="orderNo" label="订单号"  width="200" align="center"> </el-table-column>
            <el-table-column prop="carryCityName" label="售箱城市" width="120" align="center"> </el-table-column>
            <el-table-column prop="createTime" label="下单日期" width="140" align="center">
              <template #default="scope">{{ formatDate(scope.row.createTime, 4) }}</template>
            </el-table-column>
            <el-table-column prop="boxQuantity" label="箱量" width="120" align="center"> </el-table-column>
            <el-table-column prop="amount" label="订单金额" width="120" align="center">
              <template #default="scope">{{boxInfo.currency2[param.sellBoxFeeTotal.payCurrency]}}{{scope.row.amount}}</template>
            </el-table-column>
            <el-table-column prop="actualPayAmount" label="应收款项" width="120" align="center"> 
              <template #default="scope">{{boxInfo.currency2[param.sellBoxFeeTotal.payCurrency]}}{{scope.row.actualPayAmount}}</template>
            </el-table-column>
        </el-table>
        <h3>合计</h3>
        <el-row class="text-center">
          <el-col :span="6">应收箱量：{{param.sellBoxFeeTotal.payContainerNum || '--'}}</el-col>
          <el-col :span="6">应收款项总计：{{boxInfo.currency2[param.sellBoxFeeTotal.payCurrency]}} {{param.sellBoxFeeTotal.dealAmount || '--'}}</el-col>
          <el-col :span="6">实收售箱款总计：{{boxInfo.currency2[param.sellBoxFeeTotal.payCurrency]}}  {{param.sellBoxFeeTotal.deductAmount || '--'}}</el-col>
          <el-col :span="6">优惠券：{{param.sellBoxFeeTotal.couponAmount || '无'}}</el-col>
        </el-row>
      </div>
      <!-- 箱贴费 -->
      <div v-if="param.oprType == 'xiangTieFee'">
        <div style="font-weight: 700;font-size: 15px;margin-bottom: 10px">
          <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>箱贴费
        </div>
        <b>箱贴费总计</b>
        <el-table :data="param.xiangTieFeeTotal">
          <el-table-column prop="needPayContainerNum" label="应付箱量" width="120"> </el-table-column>
          <el-table-column prop="deductOverdueAmount" label="应扣超期费总计" width="120"> </el-table-column>
          <el-table-column prop="dealAmount" label="应付箱贴费总计" width="120"> </el-table-column>
          <el-table-column prop="annulOverdueAmount" label="减免超期费总计" width="120"> </el-table-column>
          <el-table-column prop="paymentOverdueAmount" label="实扣超期费总计" width="120"> </el-table-column>
          <el-table-column prop="deductElseAmount" label="实扣其他费总计" width="120"> </el-table-column>
          <el-table-column prop="deductAmount" label="实付箱贴费总计"> </el-table-column>
        </el-table>
        <b>箱贴费明细</b>
        <el-table :data="param.xiangTieFeeDetail">
          <el-table-column type="index" label="序号" width="60"> </el-table-column>
          <el-table-column prop="containerNo" label="箱号"> </el-table-column>
          <el-table-column label="箱型" width="120">
            <template v-slot="scope">
              {{ param.containerTypeFilter[scope.row.containerType] }}
            </template>
          </el-table-column>
          <el-table-column prop="unitPrice" label="箱贴费($)" width="120"> </el-table-column>
          <el-table-column prop="overdueDays" label="超期天数" width="120"> </el-table-column>
          <el-table-column prop="overdueFee" label="超期费($)" width="120"> </el-table-column>
          <el-table-column prop="dealAmount" label="应付箱贴费($)" width="120"> </el-table-column>
        </el-table>
      </div>
      <!-- 租箱款 -->
      <div v-if="param.oprType == 'rentFee'">
        <div style="font-weight: 700;font-size: 15px;margin-bottom: 10px">
          <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>租箱款
        </div>
        <b>租箱费总计</b>
        <el-table :data="param.rentFeeTotal">
          <el-table-column prop="needPayContainerNum" label="应收箱量"> </el-table-column>
          <el-table-column prop="dealAmount" label="应收租箱费总计"> </el-table-column>
          <el-table-column prop="deductAmount" label="实收租箱费总计" width="120"> </el-table-column>
        </el-table>
        <b>租箱费明细</b>
        <el-table :data="param.rentFeeDetail">
          <el-table-column type="index" label="序号" width="60"> </el-table-column>
          <el-table-column prop="orderNo" label="订单号"> </el-table-column>
          <el-table-column prop="planPickupDate" label="预计提箱日期" width="120"> </el-table-column>
          <el-table-column prop="createTime" label="下单日期" width="120"> </el-table-column>
          <el-table-column prop="packedQuantity" label="实提箱量" width="120"> </el-table-column>
          <el-table-column prop="unitPrice" label="租箱款单价($)" width="120"> </el-table-column>
          <el-table-column prop="actualPayAmount" label="应收租箱款($)" width="120"> </el-table-column>
        </el-table>
      </div>
      <!-- 支付 -->
      <div v-if="param.oprType == 'pay'">
        <div style="font-weight: 700;font-size: 15px;margin-bottom: 10px">
          <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>
          <span v-if="param.invoiceInfo.invoiceSource == 5">支付 租箱费</span>
          <span v-if="param.invoiceInfo.invoiceSource == 15">支付 购箱费</span>
        </div>
        <b>总计</b>
        <el-table :data="param.payTotal">
          <el-table-column prop="needPayContainerNum" label="应付箱量"> </el-table-column>
          <el-table-column prop="dealAmount" label="应付总计"> </el-table-column>
          <el-table-column prop="deductAmount" label="实付总计" width="120"> </el-table-column>
        </el-table>
        <b>明细</b>
        <el-table :data="param.payDetail">
          <el-table-column prop="orderNo" label="订单号" width="220"> </el-table-column>
          <el-table-column prop="carryCityName" :label="param.invoiceInfo.invoiceSource == 15 ? '购箱城市' : '租箱城市'"
            width="120">
          </el-table-column>
          <el-table-column prop="createTime" label="下单日期"> </el-table-column>
          <el-table-column prop="boxQuantity" label="箱量" width="120"> </el-table-column>
          <el-table-column prop="amount" label="订单金额(￥)" width="120"> </el-table-column>
        </el-table>
        <el-form label-width="200" style="margin: 50px 0 50px 100px;">
          <el-form-item label="优惠券">{{ 0 }}</el-form-item>
          <el-form-item label="支付方式">
            <el-select v-model="param.paymentMethod" style="width:220px" placeholder="选择">
              <el-option label="对公转账" value="5" />
              <el-option label="在线支付" value="10" />
              <!-- <el-option label="形式发票" value="15" /> -->
            </el-select>
          </el-form-item>
          <el-form-item label="电子回执单">
            <input type="file" />
          </el-form-item>
          <el-form-item label="支付日期">
            <el-date-picker v-model="param.paymentDate" type="date" placeholder="选择日期" />
          </el-form-item>
        </el-form>
      </div>
      <!-- 开发票-售箱 -->
      <div v-if="param.oprType == 'invoice'">
        <span class="_before">开发票-售箱</span>
        <div class="marginTop10">
          <!-- <b>明细</b> -->
          <el-table :data="param.orderDetail"  align="center">
            <el-table-column prop="orderNo" label="订单号" width="200" align="center"> </el-table-column>
            <el-table-column prop="carryCityName" label="购箱城市" width="80" align="center"> </el-table-column>
            <el-table-column prop="createTime" label="下单日期" width="100" align="center">
              <template v-slot="scope">
                {{ formatDate(scope.row.createTime, 2) }}
              </template>
            </el-table-column>
            <el-table-column prop="boxQuantity" label="箱量" align="center" width="70"> </el-table-column>
            <el-table-column prop="actualPayAmount" :label="'订单金额(' + payCurrency + ')'" width="100" align="center"> </el-table-column>
            <el-table-column prop="amount" :label="'应收购箱款(' + payCurrency + ')'" align="center" width="130"> </el-table-column>
          </el-table>
        </div>
        <el-form label-width="200" style="margin: 10px 0 50px 100px;">
          <el-form-item label="应收箱量：" v-if="param.invoiceInfo" style="width: 400px;">
            {{ param.invoiceInfo.payContainerNum }} 个
          </el-form-item>
          <el-form-item label="应收购箱款总计：" style="width: 400px;">
            <el-col :span="2">{{ payCurrency }}</el-col>
            <el-col :span="22">{{ param.invoiceInfo.dealAmount }}</el-col>
          </el-form-item>
          <el-form-item label="实收购箱款总计：" style="width: 400px;">
            <el-col :span="2">{{ payCurrency }}</el-col>
            <el-col :span="22">
              {{param.deductAmount}}
              <!-- <el-input-number v-model="param.deductAmount" :controls="false" 
              :formatter="(value) => value.replace(/[^0-9]/g, '')" :parser="(value) => value.replace(/[^0-9]/g, '')"/> -->
            </el-col>
          </el-form-item>
          <el-form-item label="结算币种：">
            <el-radio-group v-model="param.payCurrency">
              <el-radio value="CNY" size="large">人民币（CNY）</el-radio>
              <el-radio value="USD" size="large">美元（USD）</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="showRate" label="执行汇率：">
            1 美元 = <el-input-number v-model="param.rate" min="0" max="99.99"  :precision="2" :controls="false" />元
          </el-form-item>
          <el-form-item label="企业名称：">{{ invoice.businessName }}</el-form-item>
          <el-form-item label="统一社会信用代码：">{{ invoice.creditCode }}</el-form-item>
          <el-form-item label="申请发票类型：">{{ param.invoiceTypeFilter[invoice.invoiceType] }}</el-form-item>
          <el-form-item label="发票类型：">
            <el-select v-model="param.invoiceType" style="width:200px" placeholder="请选择">
              <el-option v-for="item in param.invoiceTypes" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="发票：">
            <imgUpload ref="invoiceRef" :needOcr="true" :drag="false" @ocrInvoiceNo="ocrInvoiceNo"></imgUpload>
          </el-form-item>
          <el-form-item label="发票号：" style="width: 500px;">
            <el-input-number v-model="invoice.invoiceNo" style="width: 100%;" :controls="false" min="10000000" max="99999999999999999999" placeholder="请输入发票号" />
          </el-form-item>
        </el-form>
      </div>
      <!-- 重开发票 -->
      <div v-if="param.oprType == 'reInvoice'">
        <div style="font-weight: 700;font-size: 15px;margin-bottom: 10px">
          <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>重开发票
        </div>
        <div>
          <b>售箱订单</b>
          <el-table v-if="param.reInvoiceDetail.purchaseBoxOrderBean"
            :data="param.reInvoiceDetail.purchaseBoxOrderBean">
            <el-table-column prop="orderNo" label="订单号"> </el-table-column>
            <el-table-column prop="amount" label="订单金额（￥）"> </el-table-column>
            <el-table-column prop="amount" label="应收售箱款（￥）"> </el-table-column>
            <el-table-column prop="refundPayAmount" label="实退售箱款（￥）"> </el-table-column>
            <el-table-column prop="conventAmount" label="实收售箱款（￥）"> </el-table-column>
          </el-table>
        </div>
        <el-form label-width="200" style="margin: 50px 0 50px 100px;">
          <el-form-item label="应收售箱款总计：">￥ {{ param.reInvoiceDetail.sumDealAmount }}</el-form-item>
          <el-form-item label="实收售箱款总计：">￥ {{ param.reInvoiceDetail.sumConventAmount }}</el-form-item>
          <el-form-item label="发票类型：">{{ param.invoiceTypeFilter[invoice.invoiceType] }}</el-form-item>
          <el-form-item label="企业名称：">{{ invoice.businessName }}</el-form-item>
          <el-form-item label="统一社会信用代码：">{{ invoice.creditCode }}</el-form-item>
          <el-form-item label="发票：">
            <input type="file" />
          </el-form-item>
          <el-form-item label="发票号：" style="width: 400px;">
            <el-input v-model="invoice.invoiceNo" placeholder="请输入发票号" />
          </el-form-item>
          <el-form-item v-if="param.oprType != 'reInvoice'" label="结算币种：">
            <el-radio-group v-model="param.payCurrency">
              <el-radio value="CNY" size="large">￥</el-radio>
              <el-radio value="USD" size="large">$</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="param.oprType != 'reInvoice'" label="执行汇率：">
            1 美元 = <el-input v-model="param.rate" style="width: 100px;"></el-input> 元
          </el-form-item>
        </el-form>
      </div>
      <!-- 红冲发票 -->
      <div v-if="param.oprType == 'redInvoice'">
        <div style="font-weight: 700;font-size: 15px;margin-bottom: 10px">
          <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>红冲发票
        </div>
        <el-form label-width="200" style="margin: 50px 0 50px 100px;">
          <el-form-item label="发票类型：">{{ param.invoiceTypeFilter[invoice.invoiceType] }}</el-form-item>
          <el-form-item label="企业名称：">{{ invoice.businessName }}</el-form-item>
          <el-form-item label="统一社会信用代码：">{{ invoice.creditCode }}</el-form-item>
          <el-form-item label="发票：">
            <input type="file" />
          </el-form-item>
          <el-form-item label="发票号：" style="width: 400px;">
            <el-input v-model="invoice.invoiceNo" placeholder="请输入发票号" />
          </el-form-item>
        </el-form>
      </div>
      <div style="text-align: center;margin-top: 20px;">
        <div class="dialog-footer">
          <el-button @click="handleClose" v-if="['xiangTieFee', 'rentFee', 'sellBoxFee', 'img'].includes(param.oprType)"
            type="primary">关闭</el-button>
          <el-button @click="handleSubmit" v-else type="primary">提交</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import pdfViewer from '@/components/pdf'
import imgUpload from '@/components/upload/index.vue'
import MultipleBoxNumbersDialog from '@/components/dialog/multipleBoxNumbersDialog'
import { formatDate } from '@/utils/index'
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
import { downloadFile } from '@/utils/download'
import { getInvoicePage, getInvoicesInfo, redPunchPurchaseBoxInvoice, reopenPunchPurchaseBoxInvoice, exportInvoice } from '@/api/invoice/index'
import { getSellPurchaseBoxOrderPage, refundPurchaseBoxOrderById, boxListDetail } from '@/api/boxDeal/boxBuy'
import { computed, onActivated, onMounted, reactive, ref } from 'vue';
import { View, List, FolderChecked, Ticket } from '@element-plus/icons-vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import boxInfo from '@/constant/containerInfo';
import { rentUploadingInvoice, callbackUploadingInvoice, payBoxLabelInvoice, purchaseBoxUploadingInvoice } from '@/api/invoice'

const customBoxInfo = {  //多箱号 提示信息
  placeholder1:'请输入订单号',
  title:'输入订单号',
  placeholder2:'请输入多个订单号以英文逗号隔开',
  button:'多订单号'
}

const param = reactive({
  payCurrency: 'CNY',
  deductAmount: 1,
  // invoiceDirection: 1, //结算流向
  invoiceDirections: [
    { value: 1, label: '收入', },
    { value: -1, label: '支出', },
  ],
  // invoiceStatus: 5, //发票状态  5-未申请 10-待开票 15-已开票 20-待红冲 25-已红冲
  invoiceStatuss: [
    { value: 5, label: '未申请'  },
    { value: 10, label: '待开票' },
    { value: 15, label: '已开票' },
    { value: 20, label: '待红冲' },
    { value: 25, label: '已红冲' }
  ],
  // closeStatus: 5, //结算状态
  closeStatuss: [ //5-未付 10-已付 15-待红冲 20-已红冲
    { value: 5, label: '未收', },
    { value: 10, label: '已收', },
    { value: 15, label: '已退', },
    // { value: 15, label: '待红冲', },
    // { value: 20, label: '已红冲', },
  ],
  invoiceType: '',
  invoiceTypes: [  //5-增值税普通发票  10-增值税专用发票 15- 形式发票
    { value: 5, label: '增值税普通发票', },
    { value: 10, label: '增值税专用发票', },
    { value: 15, label: '形式发票', },
  ],
  containerTypeFilter: { '5': '40HQ', '10': '40GP', '15': '20HQ', '20': '20GP' },
  reInvoiceDetail: [],

  radio: 0,
  loading: false,
  pageNum: 1,
  pageSize: 10,
  dialogVisible: false,
  stateFilter: { 5: '出租中', 10: '仓库中', 15: '待发布' },
  stateColor: { 15: '#22A86D', 20: '#2158F3', 25: 'red' },
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提', },
    { value: '5', label: '全新', },
  ],
  directionFilter: { '-1': '支出', '1': '收入' },
  invoiceSourceFilter: { '5': '租箱', '10': '回调', '15': '卖箱' },
  invoiceTypeFilter: { '5': '增值税普通发票', '10': '增值税专用发票', '15': '形式发票' }, //5-增值税普通发票  10-增值税专用发票
  invoiceStatusFilter: { '5': '未申请', '10': '待开票', '15': '已开票', '20': '待红冲', '25': '已红冲', '30': '已重开' },
  //5-未申请  10-待开票  15-已开票 20-待红冲 25-已红冲 30-已重开
  closeStatusFilter: { '5': '未收', '10': '已收' }, //5-未付  10-已付

  beginTotalRentQty: '',
  endTotalRentQty: '',
  boxBackCity: '',
  boxStartCity: '',
  startCityOptions: [],
  backCityOptions: [],
  typeList: [],

  invoiceTypeList: [{ value: 5, label: '增值税普通发票' }, { value: 10, label: '增值税专用发票' }, { value: 15, label: '形式发票' }],
});

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'invoiceNos', colWidth: '160', title: '发票号', type: 'text', isCheck: true },
    // { key: 'invoiceSource', colWidth: '160', title: '发票来源', type: 'filter', filter: param.invoiceSourceFilter, isCheck: true },
    { key: 'invoiceOrder', key2: 'orderNo', colWidth: '220', title: '订单号', type: '/', isCheck: true },
    { key: 'invoiceDirection', colWidth: '80', title: '结算流向', type: 'filter', filter: param.directionFilter, isCheck: true },
    { key: 'invoiceTitle', colWidth: '250', title: '结算单位', type: 'text', isCheck: true },
    { key: 'creditCode', colWidth: '150', title: '纳税人识别号', type: 'text', isCheck: true },
    { key: 'invoiceType', colWidth: '150', title: '发票类型', type: 'filter', filter: param.invoiceTypeFilter, isCheck: true },
    { key: 'invoiceAmount', colWidth: '150', title: '开票金额', type: 'add',currency:"payCurrency", isCheck: true },
    { key: 'operate', colWidth: '100', title: '款项明细', type: 'operate', isCheck: true, buttons: [{ icon: 'List', command: 'activInfo', }] },
    { key: 'invoiceStatus', colWidth: '120', title: '发票状态', type: 'filter', filter: param.invoiceStatusFilter, cFilter: param.stateColor, isCheck: true },
    { key: 'createTime', colWidth: '150', title: '申请日期', type: 'date', isCheck: true },
    // { key: 'closeStatus', colWidth: '100', title: '结算状态', type: 'filter', filter: param.closeStatusFilter, cFilter: param.stateColor, isCheck: true },
    { key: 'closeStatus', colWidth: '120', title: '结算状态', type: 'filter2', key2:"invoiceDirection", isCheck: true },

    {
      key: 'operate',
      colWidth: '200',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          icon: 'FolderChecked',
          content: "支付",
          command: 'activPay',
          isShow: (row: any) => {
            return row.invoiceStatus == '15' && row.invoiceSource != 10 && row.closeStatus == '5' && row.invoiceDirection != 1;
          },
        },
        {
          icon: 'View',
          content: "查看发票",
          command: 'showInvoice',
          isShow: (row: any) => {
            return row.invoiceStatus == '15';
          },
        },
        {
          icon: 'Ticket',
          content: "开发票",
          command: 'applyInvoice',
          isShow: (row: any) => {
            return row.invoiceStatus < 15 && row.invoiceSource == 15;
          },
        },
        {
          icon: 'Ticket',
          content: "重开发票",
          command: 'reInvoice',
          isShow: (row: any) => {
            return row.invoiceStatus == 25 && row.invoiceSource == 15;
          },
        },
        {
          icon: 'Ticket',
          content: "红冲发票",
          command: 'applyRedInvoice',
          isShow: (row: any) => {
            return row.invoiceStatus == 20 && row.invoiceSource == 15;
          },
        },
      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});

function handleTypeChange(val: any) {
  param.status = val
  getTableData()
}

// 获取列表数据
function getTableData() {
  let data = {
    invoiceSources: [15], //发票订单来源(5-租箱 10-回调 15-购箱)
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    invoiceDirection: param.invoiceDirection,
    orderNo: param.orderNo?.toUpperCase(),
    invoiceTitle: param.businessName,
    invoiceNo: param.invoiceNoSearch?.toUpperCase(),
    invoiceStatus: param.invoiceStatus,
    invoiceType: param.invoiceType,
    creditCode: param.creditCode?.toUpperCase(),
    closeStatus: param.closeStatus
  };
  if (param.createDate) {
    data.beginCreateDate = param.createDate[0]
    data.endCreateDate = param.createDate[1]
  }
  table.config.loading = true;
  // 获取列表数据
  getInvoicePage(data).then((res: any) => {
    table.data = JSON.parse(JSON.stringify(res.data.list));
    table.data.map((item: any) => {
      item.invoiceNos = item.invoiceNo
    })
    table.config.total = res.data.total;
  });
  table.config.loading = false;
}

// 重置
function handleReset() {
  param.invoiceStatus = null
  param.invoiceDirection = null
  param.orderNo = null
  param.businessName = null
  param.invoiceNoSearch = null
  param.invoiceStatus = null
  param.invoiceType = null
  param.creditCode = null
  param.closeStatus = null
  param.createDate = null
  getTableData()
}

// 发票识别
const ocrInvoiceNo = (val: any) => {
  invoice.value.invoiceNo = val.data.invoiceNo
}

//上架/下架  
const tableRef = ref({ multipleSelection: [] })
const selection = computed(() => {
  let ids: any[] = []
  tableRef.value.multipleSelection.map((item: any) => {
    ids.push(item.id)
  })
  return ids
})

// 箱贴费/租箱款
const activInfo = (row: any) => {
  switch (row.invoiceSource) { //invoiceSource:发票来源  5-租箱  10-回调 15-售箱 
    case 5:
      param.oprType = 'rentFee'
      break
    case 10:
      param.oprType = 'xiangTieFee'
      break
    case 15:
      param.oprType = 'sellBoxFee'
      break
    default:
      param.oprType = ''
      break
  }
  getDetailAndTotal(row)
}

// 查看发票
let invoice = ref({})
const showInvoice = (row: any) => {
  param.oprType = 'img'
  param.pdfUrl = JSON.parse(row.invoiceUrl) || []
  param.dialogVisible = true
}

//支付
const activPay = (row: any) => {
  param.oprType = 'pay'
  invoice.value = row
  getDetailAndTotal(row)
}
//开发票
const payCurrency = computed(() => param.invoiceInfo.payCurrency == 'CNY' ? '¥' : '$')
const showRate = computed(() => param.payCurrency != param.invoiceInfo.payCurrency)
const applyInvoice = (row: any) => {
  param.oprType = 'invoice'
  invoice.value = row
  getDetailAndTotal(row)
}
//红冲发票
const applyRedInvoice = (row: any) => {
  param.oprType = 'redInvoice'
  invoice.value = row
  getDetailAndTotal(row)
}
//重开发票
const reInvoice = (row: any) => {
  param.oprType = 'reInvoice'
  invoice.value = row
  getBoxListDetail(row)
}

//聚合提交
const invoiceRef = ref()
const handleSubmit = () => {
  const oprType = param.oprType
  if (oprType == 'pay') {
    // 支付箱贴费
    const data = {
      "id": invoice.value.id,
      "paymentMethod": param.paymentMethod,//5-对公转账  10-在线支付 15-形式发票
      "payDate": param.paymentDate,
      "payUrl": "[{\"name\":\"20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\",\"returnReceiptFileName\":\"国际贸易供应链数字平台电子回执单.docx\",\"url\":\"http://47.122.3.254:9000/default/20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\"}]"
    }
    payBoxLabelInvoice(data).then((res: any) => {
      getTableData()
      param.dialogVisible = false
    })
    return
  }
  // if (!invoice.invoiceNo) {
  //   return ElMessage.error('请输入发票号')
  // }
  if (oprType == 'invoice') {
    if (invoice.value.invoiceNo=='') {
      return ElMessage.warning('请输入发票号')
    }
    if (!param.deductAmount) {
      return ElMessage.warning('请输入实收购箱款')
    }
    // 开发票
    // const invoiceId = invoice.value.id
    const invoiceUrl = invoiceRef.value.resultList || []
    const data = {
      "id": invoice.value.id,
      "invoiceNo": invoice.value.invoiceNo,
      "invoiceUrl": JSON.stringify(invoiceUrl),
      "rate": showRate ? param.rate : null,
      "payCurrency": param.payCurrency,
      "invoiceType": param.invoiceType
    }
    // console.log(typeof invoice.value.id)
    // return
    purchaseBoxUploadingInvoice(data).then((res: any) => {
      getTableData()
      param.dialogVisible = false
    })
  }
  if (oprType == 'redInvoice') {
    if (invoice.value.invoiceNo=='') {
      return ElMessage.error('请输入发票号')
    }
    const data = {
      "id": invoice.value.id,
      "invoiceNo": invoice.value.invoiceNo,
      "redInvoiceUrl": "[{\"name\":\"20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\",\"invoiceFileName\":\"国际贸易供应链数字平台需求分析(1).docx\",\"url\":\"http://47.122.3.254:9000/default/20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\"}]"
    }
    // console.log(typeof invoice.value.id)
    // return
    redPunchPurchaseBoxInvoice(data).then((res: any) => {
      getTableData()
      param.dialogVisible = false
    })
  }
  if (oprType == 'reInvoice') {
    if (invoice.value.invoiceNo=='') {
      return ElMessage.error('请输入发票号')
    }
    {
      const data = {
        "invoiceOrder": "[{\"orderId\": 5,\"orderNo\": \"MYOID2024083008103914\"},{\"orderId\": 6,\"orderNo\": \"MYOID2024083004813956\"}]",
        "id": invoice.value.id,
        "invoiceNo": invoice.value.invoiceNo,
        "redInvoiceUrl": "[{\"name\":\"20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\",\"invoiceFileName\":\"国际贸易供应链数字平台需求分析(1).docx\",\"url\":\"http://47.122.3.254:9000/default/20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\"}]"
      }
      reopenPunchPurchaseBoxInvoice(data).then((res: any) => {
        getTableData()
        param.dialogVisible = false
      })
    }
  }
}

//获取详情 
function getDetailAndTotal(val: any) {
  getInvoicesInfo(val.id).then((res: any) => {
    const invoicesInfo = res.data
    param.invoiceInfo = res.data
    switch (param.oprType) {
      case 'rentFee':
        param.rentFeeDetail = JSON.parse(res.data.containerNoDetail) || []
        param.rentFeeTotal = [{ needPayContainerNum: param.rentFeeDetail.length, deductAmount: invoicesInfo.deductAmount, dealAmount: invoicesInfo.dealAmount }]
        break
      case 'xiangTieFee':
        param.xiangTieFeeDetail = JSON.parse(res.data.containerNoDetail) || []
        param.xiangTieFeeTotal = [{ needPayContainerNum: param.xiangTieFeeDetail.length, deductOverdueAmount: invoicesInfo.deductOverdueAmount, dealAmount: invoicesInfo.dealAmount, annulOverdueAmount: invoicesInfo.annulOverdueAmount, paymentOverdueAmount: invoicesInfo.paymentOverdueAmount, deductAmount: invoicesInfo.deductAmount, deductElseAmount: invoicesInfo.deductElseAmount }]
        break
      case 'sellBoxFee':
        param.sellBoxFeeDetail = JSON.parse(res.data.containerNoDetail) || []
        param.sellBoxFeeTotal = {payCurrency:invoicesInfo.payCurrency, payContainerNum: invoicesInfo.payContainerNum, deductAmount: invoicesInfo.deductAmount, dealAmount: invoicesInfo.dealAmount, annulOverdueAmount: invoicesInfo.annulOverdueAmount, paymentOverdueAmount: invoicesInfo.paymentOverdueAmount, couponAmount: invoicesInfo.couponAmount }
        break
      case 'img':
        // param.sellBoxFeeDetail = JSON.parse(res.data.containerNoDetail)
        // param.sellBoxFeeTotal = [{ needPayContainerNum: param.sellBoxFeeDetail.length, deductOverdueAmount: val.deductOverdueAmount, dealAmount: val.dealAmount, annulOverdueAmount: val.annulOverdueAmount, paymentOverdueAmount: val.paymentOverdueAmount, deductAmount: val.deductAmount }]
        break
      case 'pay':
        param.payDetail = JSON.parse(res.data.containerNoDetail)
        param.payTotal = [{ needPayContainerNum: invoicesInfo.payContainerNum, dealAmount: invoicesInfo.dealAmount, deductAmount: invoicesInfo.deductAmount }]
        break
      case 'invoice':
        param.orderDetail = JSON.parse(res.data.containerNoDetail) || []

        param.sellBoxFeeDetail = JSON.parse(res.data.containerNoDetail)
        param.sellBoxFeeTotal = [{ needPayContainerNum: param.sellBoxFeeDetail.length, deductOverdueAmount: val.deductOverdueAmount, dealAmount: val.dealAmount, annulOverdueAmount: val.annulOverdueAmount, paymentOverdueAmount: val.paymentOverdueAmount, deductAmount: val.deductAmount }]
        break
      case 'reInvoice':
        break
      case 'redInvoice': //红冲 同 invoice
        param.xiangTieFeeDetail = JSON.parse(res.data.containerNoDetail) || []
        param.xiangTieFeeTotal = [{ needPayContainerNum: param.xiangTieFeeDetail.length, deductOverdueAmount: invoicesInfo.deductOverdueAmount, dealAmount: invoicesInfo.dealAmount, annulOverdueAmount: invoicesInfo.annulOverdueAmount, paymentOverdueAmount: invoicesInfo.paymentOverdueAmount, deductAmount: invoicesInfo.deductAmount }]

        param.sellBoxFeeDetail = JSON.parse(res.data.containerNoDetail)
        param.sellBoxFeeTotal = [{ needPayContainerNum: param.sellBoxFeeDetail.length, deductOverdueAmount: val.deductOverdueAmount, dealAmount: val.dealAmount, annulOverdueAmount: val.annulOverdueAmount, paymentOverdueAmount: val.paymentOverdueAmount, deductAmount: val.deductAmount }]
        break
      default:
        param.oprType = ''
        break
    }
    param.dialogVisible = true
  })
}
//重开发票 售箱订单明细
function getBoxListDetail(val: any) {
  const invoiceOrder = JSON.parse(val.invoiceOrder)
  const ids = invoiceOrder.map((item: any) => item.orderId)
  const data: any = { "purchaseIds": ids }
  boxListDetail(data).then((res: any) => {
    param.reInvoiceDetail = res.data
  })
  param.dialogVisible = true
}

function handleClose() {
  param.dialogVisible = false
}

//分页
function onTablePageChange(page: { pageNum: number; pageSize: number }) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

onActivated(() => {
  getTableData()
})

const toExportInvoice = () => { 
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  const ids = checkAllItem.map((item: any) => item.id)

    if (ids.length < 1) return ElMessage.warning('请选择需要导出的发票！')
    ElMessageBox.confirm('确认要导出选中的发票？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        let reqParameters = {
          invoiceIds: ids
        }
        exportInvoice(reqParameters).then((res: any) => {
            downloadFile(res, '发票详情')
          
        }).catch((error) => {
            ElMessage.error(error)
        })
    }).catch(() => {
        // ElMessage.warning('请选择要收取的箱号！')
    })
}
const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）

const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const slectAll = async(val:any) =>{
    checkAll.value = []
    await getInvoicePage({ pageNum:1,pageSize:10000}).then(res =>{ 
      if(res.code == "00000" && res.data.list && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}


</script>

<style scoped>
.hide-spin-buttons input::-webkit-outer-spin-button,
.hide-spin-buttons input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
/* Firefox */
.hide-spin-buttons input[type=number] {
  -moz-appearance: textfield;
}
</style>